package com.hddz.comlib;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import android.util.Log;

public class PrintSerialHelper {
	private static final String TAG = "PrintSerialHelper";
	private static final String DEVFILE_PATH = "/proc/driver/printer";
	private static final String SERIALPORT_PATH = "/dev/eser1";
	private DeviceControl mdevCtrl = null;
	private SerialPort mSerialPort = null;
	private OutputStream mOutputStream;

	/**
	 * 连接NFC串口，开始读取
	 * 
	 * @return
	 */
	public Boolean startPrintSerial() {
		try {
			mdevCtrl = new DeviceControl(DEVFILE_PATH);
			mSerialPort = new SerialPort(new File(SERIALPORT_PATH), 9600, 0);
			mOutputStream = mSerialPort.getOutputStream();
			mdevCtrl.PowerOnDevice();
			return true;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 停止NFC串口
	 * 
	 * @return
	 */
	public Boolean stopPrintSerial() {
		try {
			if (mOutputStream != null) {
				mOutputStream.close();
				mOutputStream = null;
			}
			if (mdevCtrl != null) {
				mdevCtrl.PowerOffDevice();
				mdevCtrl = null;
			}
			if (mSerialPort != null) {
				mSerialPort.close();
				mSerialPort = null;
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public Boolean print(byte[] buf) {
		try {
			mOutputStream.write(buf);
			mOutputStream.flush();
			String s = "";
			for (int i = 0; i < buf.length; i++) {
				s += String.format("%X ", buf[i]);
			}
			Log.d(TAG, "send=>" + s);
			return true;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}

	public Boolean print(String buf) {
		Log.d(TAG, "send=>" + buf);
		return print(buf.getBytes());
	}
	
}
